var http = require('http');


var https = require('https');

var URL = require('url').URL;
var fs = require('fs');

var downloadFile = function (uri, dest, callback) {
    // 确保dest路径存在

    var  obj = new URL(uri);
    var ccv = http;
    if (obj.protocol == "https:") {
          ccv = https;
    }
    var file = fs.createWriteStream(dest);

    ccv.get(uri, function (res) {
        if (res.statusCode !== 200) {
            callback(res.response.statusCode);
            return;
        }

        res.on('end', function () {

            //callback({error:0});
           // console.log('download end');
        });

        // 进度、超时等

        file.on('finish', function () {
           // console.log('finish write file')
            file.close(callback);
        }).on('error', function (err) {
            fs.unlink(dest);
            if (callback) {
                callback(err.message);
            }
        })
        res.pipe(file);
    });
}


module.exports = downloadFile;